//
//  ViewController.m
//  摇奖机
//
//  Created by 伍银荣 on 2021/8/27.
//  Copyright © 2021 com.WYR. All rights reserved.
//

#import "ViewController.h"
#import "Person.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *lbl1;
@property (weak, nonatomic) IBOutlet UILabel *lbl2;
@property (weak, nonatomic) IBOutlet UILabel *lbl3;
@property (weak, nonatomic) IBOutlet UIButton *drawBtn;

@property (nonatomic, strong) NSOperationQueue *queue;
@end

@implementation ViewController

//懒加载
-(NSOperationQueue *)queue {
    if (!_queue) {
        _queue = [[NSOperationQueue alloc]init];
    }
    return _queue;
}

- (IBAction)buttonClick:(UIButton *)sender {
    if(self.queue.operationCount == 0) {
        //如果此时操作数为0的话就开始显示随机数
        //循环是一个耗时操作,所以应该把它放到一个子线程中,异步操作
        [self.queue addOperationWithBlock:^{
           [self labelText];
        }];
        //点击按钮就开始暂停
        self.queue.suspended = NO;
        [self.drawBtn setTitle:@"暂停" forState:UIControlStateNormal];
    } else if (!self.queue.isSuspended){
        //先把当前正在执行的操作执行完毕,暂停后续的操作
        self.queue.suspended = YES;
        [self.drawBtn setTitle:@"继续" forState:UIControlStateNormal];
    }
    // NSLog(@"队列的操作数:%zd",self.queue.operationCount);
    NSLog(@"主线程队列State:%d", self.queue.isSuspended);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"-----队列的操作数:%zd",self.queue.operationCount);
//
//    Person *p1 = [[Person alloc]init];
//    [p1 copy];
}

//获取label的随机数
- (void)labelText {
    int i = 0;
    NSLog(@"1-子线程队列State:%d", self.queue.isSuspended);
    while (!self.queue.isSuspended) {
        // NSLog(@"2-子线程队列State:%d", self.queue.isSuspended);
        [NSThread sleepForTimeInterval:0.05];
            //获取0到9之间的随机数  [0, 9)
            int num1 = arc4random_uniform(10);
            int num2 = arc4random_uniform(10);
            int num3 = arc4random_uniform(10);
        
        //lbl的文字显示要放到主线程执行的,所以此时应该切换到主线程中执行
        i = i + 1;
        NSLog(@"开始第%d次随机", i);
        // Async main 1
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            NSLog(@"正在执行第%d次随机", i);
            self.lbl1.text = [NSString stringWithFormat:@"%d",num1];
            self.lbl2.text = [NSString stringWithFormat:@"%d",num2];
            self.lbl3.text = [NSString stringWithFormat:@"%d",num3];
        }];
        NSLog(@"结束第%d次随机", i);
    }
}


@end
